<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="auto"
      >
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['authRule/create']"
            type="success"
            icon="plus"
            @click="handleOpenDialog('0')"
          >
            新增
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        row-key="id"
        :data="menuTableData"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        class="data-table__content"
        @row-click="handleRowClick"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <template
              v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')"
            >
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <div :class="`i-svg:${scope.row.icon}`" />
            </template>
            {{ scope.row.title }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <!-- 0目录，1菜单，2页面，3按钮元素，4接口 -->
            <el-tag v-if="scope.row.type === 0" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === 1" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type === 2" type="primary">页面</el-tag>
            <el-tag v-if="scope.row.type === 3" type="danger">按钮</el-tag>
            <el-tag v-if="scope.row.type === 4" type="info">接口</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="请求类型" align="center" width="80">
          <template #default="scope">
            <!-- 0无，1get，2post，3delete，4put -->
            <el-tag v-if="scope.row.api_method === 0" type="warning">无</el-tag>
            <el-tag v-if="scope.row.api_method === 1" type="success">
              GET
            </el-tag>
            <el-tag v-if="scope.row.api_method === 2" type="primary">
              POST
            </el-tag>
            <el-tag v-if="scope.row.api_method === 3" type="danger">
              DELETE
            </el-tag>
            <el-tag v-if="scope.row.api_method === 4" type="info">PUT</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="路由名称"
          align="left"
          width="150"
          prop="name"
        />
        <el-table-column label="路由路径" align="left" width="150" prop="url" />
        <el-table-column
          label="路由参数"
          align="left"
          width="150"
          prop="url_param"
        />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80" prop="rank" />
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == 0 || scope.row.type == 1"
              v-hasPerm="['authRule/create']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              新增
            </el-button>

            <el-button
              v-hasPerm="['authRule/update']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['authRule/delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parent_id"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单标识" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单标识" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group
            v-model="formData.type"
            @change="handleMenuTypeChange"
          >
            <!--  菜单类型，0目录，1菜单，2页面，3按钮元素，4接口 -->
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">菜单</el-radio>
            <el-radio :value="2">页面</el-radio>
            <el-radio :value="3">按钮元素</el-radio>
            <el-radio :value="4">接口</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请求类型" prop="api_method">
          <el-radio-group v-model="formData.api_method">
            <!--  接口类型，0无，1get，2post，3delete，4put -->
            <el-radio :value="0">无</el-radio>
            <el-radio :value="1">GET</el-radio>
            <el-radio :value="2">POST</el-radio>
            <el-radio :value="3">DELETE</el-radio>
            <el-radio :value="4">PUT</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>
        <el-form-item label="路由url" prop="url">
          <el-input v-model="formData.url" placeholder="请输入路由url" />
        </el-form-item>
        <el-form-item label="路由url参数" prop="url_param">
          <el-input
            v-model="formData.url_param"
            placeholder="请输入路由url参数"
          />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="rank">
          <el-input-number
            v-model="formData.rank"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";

import RuleAPI, { RulePageQuery, RuleInfo } from "@/api/system/rule.api";

defineOptions({
  name: "AuthRule",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const menuFormRef = ref();

const loading = ref(false);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);
// 查询参数
const queryParams = reactive<RulePageQuery>({});
// 菜单表格数据
const menuTableData = ref<RuleInfo[]>([]);
// 顶级菜单下拉选项
const menuOptions = ref<OptionType[]>([]);
// 初始菜单表单数据
const initialMenuFormData = ref<RuleInfo>({
  /** 菜单ID */
  id: "",
  /** 菜单名称 */
  title: "",
  /** 菜单唯一标识 */
  name: "",
  /** 菜单URL */
  url: "",
  /** 路由参数 */
  url_param: "",
  /** 图标 */
  icon: "",
  /** 菜单类型，0目录，1菜单，2页面，3按钮元素，4接口 */
  type: 0,
  /** 接口类型，0无，1get，2post，3delete，4put */
  api_method: 1,
  /** 排序，数值越大权重越高 */
  rank: 0,
  /** 父级ID */
  parent_id: "",
  /** 菜单状态：2禁用，1正常 */
  status: 1,
});
// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });
// 表单验证规则
const rules = reactive({
  title: [{ required: true, message: "请输入菜单标题", trigger: "blur" }],
  parent_id: [{ required: true, message: "请选择父级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedMenuId = ref<string | undefined>();

// 查询菜单
function handleQuery() {
  loading.value = true;
  RuleAPI.getPage(queryParams)
    .then((data) => {
      menuTableData.value = data.list;
      menuOptions.value = data.options;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.keywords = "";
  handleQuery();
}

// 行点击事件
function handleRowClick(row: RuleInfo) {
  selectedMenuId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function handleOpenDialog(parentId?: string, data?: RuleInfo) {
  dialog.visible = true;
  if (data?.id) {
    dialog.title = "编辑菜单";
    //复制 data 给formData.value
    Object.assign(formData.value, data);
  } else {
    dialog.title = "新增菜单";
    Object.assign(formData.value, initialMenuFormData.value);
    formData.value.parent_id = parentId ?? "0";
  }
}

// 菜单类型切换
function handleMenuTypeChange() {
  // 如果菜单类型改变
  if (formData.value.type !== initialMenuFormData.value.type) {
    // 目录切换到菜单时，清空组件路径
    if (initialMenuFormData.value.type === 0) {
      formData.value.url = "";
    } else {
      // 其他情况，保留原有的组件路径
      formData.value.url = initialMenuFormData.value.url;
      formData.value.url_param = initialMenuFormData.value.url_param;
    }
  }
}

/**
 * 提交表单
 */
function handleSubmit() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id;
      if (menuId) {
        //修改时父级菜单不能为当前菜单
        if (formData.value.parent_id == menuId) {
          ElMessage.error("父级菜单不能为当前菜单");
          return;
        }
        RuleAPI.update(formData.value).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        });
      } else {
        RuleAPI.create(formData.value).then(() => {
          ElMessage.success("新增成功");
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除菜单
function handleDelete(menuId: string) {
  const menuIds = [menuId].join(",");
  if (!menuIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RuleAPI.deleteByIds({ ids: menuIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  // formData.value = {
  //   /** 菜单ID */
  //   id: "",
  //   /** 菜单名称 */
  //   title: "",
  //   /** 菜单唯一标识 */
  //   name: "",
  //   /** 菜单URL */
  //   url: "",
  //   /** 路由参数 */
  //   url_param: "",
  //   /** 图标 */
  //   icon: "",
  //   /** 菜单类型，0目录，1菜单，2页面，3按钮元素，4接口 */
  //   type: 0,
  //   /** 接口类型，0无，1get，2post，3delete，4put */
  //   api_method: 1,
  //   /** 排序，数值越大权重越高 */
  //   rank: 0,
  //   /** 父级ID */
  //   parent_id: "",
  //   /** 菜单状态：2禁用，1正常 */
  //   status: 1,
  // };
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
